import sys
import json
import time
import datetime
import random

import paho.mqtt.client as mqtt

host_ip = '101.37.80.37'
direction = 0


def on_connect(client, userdata, flags, rc):
    print('Connected with result code: ' + str(rc))


def on_message(client, userdata, msg):
    print(msg.topic + ': ' + str(msg.payload))


def main():
    # 参数依次为deviceId，channelId
    if len(sys.argv) < 4:
        print('参数过少，格式为：python file.py sleep_seconds device_id channel_id data_field...')
        return
    sleep_seconds = eval(sys.argv[1])
    deviceId = eval(sys.argv[2])
    channelId = eval(sys.argv[3])
    topic = str(channelId)

    mqttc = mqtt.Client('device' + str(deviceId))
    mqttc.on_connect = on_connect
    mqttc.on_message = on_message
    mqttc.connect(host_ip, 1883, 60)

    data = []
    message = {'topic': topic,
               'deviceId': deviceId,
               'channelId': channelId,
               'direction': direction,
               'data': data}
    while True:
        data.clear()
        for field in sys.argv[4:]:
            data.append({field: random.uniform(0, 50)})
        message['date'] = str(datetime.datetime.now())
        mqttc.publish(topic, payload=json.dumps(message), qos=0)
        mqttc.loop_start()
        time.sleep(sleep_seconds)


if __name__ == '__main__':
    main()
